package com.vgooo.client.myvg;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.message.BasicNameValuePair;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;
import com.vgooo.bean.UserInfo;
import com.vgooo.client.Constants;
import com.vgooo.client.Main;
import com.vgooo.client.R;
import com.vgooo.client.VGActivity;
import com.vgooo.client.VGApplication;
import com.vgooo.client.ViewLayout;
import com.vgooo.client.myvg.weibo.keeper.AccessTokenKeeper;
import com.vgooo.util.BitmapUtils;
import com.vgooo.util.DebugTools;
import com.vgooo.util.GSonTools;
import com.vgooo.util.HttpUtils;
import com.vgooo.util.MD5Utils;
import com.vgooo.util.TimeUtils;
import com.vgooo.util.UmengUtils;
import com.vgooo.util.Utils;

public class MyVGActivity extends VGActivity {

	private String className = "MyVGActivity";// 类名， 用于调试

	private UserInfo userInfo;

	private TextView userName;// 用户名（邮箱）、

	private ImageView imageBig;// 大头像
	private TextView nickName;// 呢称
	private TextView sexMale,sexFemale ;//性别
	private TextView address;// 来自
	private TextView effectCash;// 我的基金
	private TextView ping ;//评论数
	

	private AlertDialog dialog;// 修改密码的对话框
	private EditText oldPwd;// 旧密码文本框
	private EditText newPwd1;// 新密码文本框
	private EditText newPwd2;// 确认新密码文本框


	Context context = this;

	private Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		detailVeiw = inflater.inflate(R.layout.my_vg_user_info, null);
		setContentView(detailVeiw);
		detailVeiw.setVisibility(View.INVISIBLE);
		initView();
		addListener();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		// 友盟统计功能，打开页面
		MobclickAgent.onResume(this);
		super.onResume();
		userInfo = VGApplication.userInfo;
		if (userInfo != null && userInfo.isLogin 
				&& userInfo.user_id != null
				&& !userInfo.user_id.equals("")
				) {
			if(userInfo.otherLogin==OtherLogin.TYPE_QQ||userInfo.otherLogin==OtherLogin.TYPE_WEI_BO){
				setupView();
				return ;
			}
			init();
//			try {
//				getData();
//				setupView();
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//				UmengUtils.onError(this, e.toString());
//			}
		} else {
			ViewLayout.setViewPre(true, "登录", ViewLayout.TAB_TAG_MYLOGIN,this);
//			ViewLayout.setView(true, "登录", ViewLayout.TAB_TAG_LOGIN, Main.currentTabId +3,false, this);
//			ViewLayout.setViewPre(true, "登录", ViewLayout.TAB_TAG_LOGIN,cparent);
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		// 友盟统计功能，页面关闭
		MobclickAgent.onPause(this);
	}
	
	@Override
	public void initView() {
		
		// TODO Auto-generated method stub
		userName = (TextView) findViewById(R.id.my_vg_user_info_account);
		imageBig = (ImageView) findViewById(R.id.my_vg_user_info_thumb);
		nickName = (TextView) findViewById(R.id.my_vg_user_info_nick_name);
		sexMale = (TextView) findViewById(R.id.my_vg_user_info_male_bt);
		sexFemale = (TextView) findViewById(R.id.my_vg_user_info_female_bt);
		address = (TextView) findViewById(R.id.my_vg_user_info_address);
		effectCash = (TextView) findViewById(R.id.my_vg_user_info_effect_cash);
		ping = (TextView) findViewById(R.id.my_vg_user_info_user_ping_count);

		// 修改密码对话框
		Builder builder = new Builder(this);
		builder.setTitle("修改密码");
		View view = getLayoutInflater().inflate(R.layout.my_vg_change_password,
				null);
		oldPwd = (EditText) view.findViewById(R.id.my_vg_change_password_old);
		newPwd1 = (EditText) view.findViewById(R.id.my_vg_change_password_new1);
		newPwd2 = (EditText) view.findViewById(R.id.my_vg_change_password_new2);
		builder.setView(view);
		dialog = builder.create();
	}

	@Override
	public void setupView() {
		detailVeiw.setVisibility(View.VISIBLE);
		// TODO Auto-generated method stub
		BitmapUtils.loaderImage(userInfo.shop_face, imageBig, this);
		userName.setText(userInfo.unser_name);
		nickName.setText(userInfo.nick_name);
		if(userInfo.gender==null||"1".equals(userInfo.gender)){
			chanageSex(true);
		}else{
			chanageSex(false);
		}
		DebugTools.log(className, userInfo.gender);
		address.setText(userInfo.address);
		effectCash.setText(userInfo.effect_cash);
		ping.setText(userInfo.user_ping_count+"条");

		handler = new MyHandler();
		

	}

	@Override
	public void getData(){
		
		try {
			// TODO Auto-generated method
			// stub"userinfo?uid=222728"+"&ucode=27224539f94a7b8962c67471d4b24e13"
//			String urlPath = HttpUtils.BASE_URI + "userinfo?uid="
//					+ userInfo.user_id + "&ucode="
//					+ MD5Utils.getUCode(userInfo.user_id);
//			String jsonString = HttpUtils.getJsonString(urlPath);
			String urlPath = HttpUtils.BASE_URI + "userinfo";
			Map<String,String > params = new HashMap<String, String>() ;
			params.put("uid", userInfo.user_id);
			params.put("ucode", MD5Utils.getUCode(userInfo.user_id));
			String jsonString = HttpUtils.doPost(urlPath, params);
//			ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
//			params.add(new BasicNameValuePair("uid", userInfo.user_id));
//			params.add(new BasicNameValuePair("ucode", MD5Utils.getUCode(userInfo.user_id)));
//			String jsonString = HttpUtils.getJsonString(urlPath,params);
			Map<String, Object> map = GSonTools.getObjectMaps(jsonString);
			Map<String, String> user = (Map<String, String>) map.get("user");
			userInfo.unser_name = user.get("user_name");
			userInfo.user_email = user.get("user_email");
			Map<String, String> profile = (Map<String, String>) map.get("profile");
			userInfo.nick_name = profile.get("nick_name");
			userInfo.shop_face = profile.get("shop_face");
			userInfo.gender = profile.get("gender");
			userInfo.address = profile.get("address");
			userInfo.effect_cash = profile.get("effect_cash");
			userInfo.user_ping_count = (String) map.get("user_ping_count") ;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e) ;
		}
	}

	private void chanagePwd() {

		String oldw = oldPwd.getText().toString().trim();
		String neww1 = newPwd1.getText().toString().trim();
		String neww2 = newPwd2.getText().toString().trim();
		if (oldw == null || "".equals(oldw)) {
			oldPwd.setError("请输入密码！");
			oldPwd.requestFocus();
			Utils.showSoftInput(oldPwd);
			return;
		}
		if (!VGApplication.userInfo.password.equals(oldw)) {
			oldPwd.setError("密码不正确！");
			Utils.showSoftInput(oldPwd);
			oldPwd.requestFocus();
			return;
		}
		if (neww1 == null || "".equals(neww1)) {
			newPwd1.setError("新密码不能为空！");
			newPwd1.requestFocus();
			Utils.showSoftInput(newPwd1);
			return;
		}
		if (neww1.length() < 6 || neww1.length() > 15) {
			newPwd1.setError("密码长度6-15位！");
			newPwd1.requestFocus();
			Utils.showSoftInput(newPwd1);
			return;
		}
		if (!neww1.equals(neww2)) {
			newPwd2.setError("两次输入的密码不一致！");
			newPwd2.requestFocus();
			Utils.showSoftInput(newPwd2);
			return;
		}
		Utils.hideSoftInput(newPwd2);
		UserUtils.chanagePassWord(neww1, this, handler);
		DebugTools.log(className, "old password : " + oldw);
		DebugTools.log(className, "new password : " + neww1);
	}

	@Override
	public void doClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = new Intent();
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.my_vg_user_info_logout:
			DebugTools.log(className, "你单击了 退出 ： " + "");
			userInfo.isLogin = false;
			userInfo.otherLogin = 0 ;
			AccessTokenKeeper.clear(Main.activity);
			// 更改用户信息
			UserUtils.writeUserInfo(userInfo, this);
			detailVeiw.setVisibility(View.GONE);
			ViewLayout.setViewBack();
			
			DebugTools.toast(this, "退出登录");

			break;

		case R.id.my_vg_user_info_chanage_pwd:
			DebugTools.log(className, "你单击了 修改密码 ： " + "");
			dialog.show();
			Utils.showSoftInput(oldPwd);
			break;

		case R.id.my_vg_change_password_change:// 修改
			chanagePwd();

			break;

		case R.id.my_vg_change_password_cancel:// 取消修改
			dialog.cancel();
			Utils.hideSoftInput(oldPwd);
			break;

		case R.id.my_vg_user_info_thumb_change:// 上传头像
			DebugTools.log(className, "你单击了 上传头像 ： " + "");
			ViewLayout.setViewPre(true, "上传头像", ViewLayout.TAB_TAG_PHOTO,cparent);
			break;

		default:
			DebugTools
					.log(className, "doClick() 未定义控件单击后的事件......" + v.getId());
			break;
		}
	}
	
	
	private void chanageSex(boolean isMale){
		if(isMale){
			sexMale.setBackgroundResource(R.drawable.rg_button_bg_selected);
			sexFemale.setBackgroundResource(R.drawable.rg_button_bg_inselected);
		}else{
			sexMale.setBackgroundResource(R.drawable.rg_button_bg_inselected);
			sexFemale.setBackgroundResource(R.drawable.rg_button_bg_selected);
		}
	}

	class MyHandler extends Handler {
		public void handleMessage(android.os.Message msg) {
			// String arg = (String) msg.obj ;
			Builder builder = new Builder(context);
			AlertDialog chanageDialog;
			View view = LayoutInflater.from(context).inflate(
					R.layout.chanage_info, null);
			ImageView image = (ImageView) view
					.findViewById(R.id.chanage_info_image);
			switch (msg.what) {
			case UserUtils.SUCCESS:
				dialog.cancel();
				DebugTools.log(className, "修改成功 result =  ");
				image.setImageResource(R.drawable.chanage_success);
				Toast.makeText(context, "修改成功！", Toast.LENGTH_LONG).show();
				builder.setView(view);
				chanageDialog = builder.create();
				chanageDialog.show();
				TimeUtils.TimeTask(chanageDialog, 800);
				// 修改登录状态，跳转到登录页面
				VGApplication.userInfo.isLogin = false;
				VGApplication.userInfo.password = "";
				ViewLayout.setViewPre(true, "登录", ViewLayout.TAB_TAG_LOGIN,cparent);
				break;
			case UserUtils.FAIL:
				DebugTools.log(className, "修改失败 result ");
				image.setImageResource(R.drawable.chanage_fail);
				Toast.makeText(context, "修改失败！", Toast.LENGTH_LONG).show();
				builder.setView(view);
				chanageDialog = builder.create();
				chanageDialog.show();
				TimeUtils.TimeTask(chanageDialog, 800);
				break;
			default:
				break;
			}
		};
	}
	
	
//	private static void log(String info){
//		Log.i("Main", info);
//	}

}
